#include "Precompile.h"
#include "ImageLoader.h"

namespace Utility{
	ImageDescriptionPtr ImageLoader::loadImage(std::string& filename){
		std::string filePath = Core::GeneralSettings::findFilePath(filename);
		if(filePath.empty()){
			LOG_ERROR("Image file not found.");
			assert(0);
			return ImageDescriptionPtr();
		}

		ImageDescriptionPtr imageDesc = ImageDescriptionPtr(new ImageDescription);

		FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;
		FIBITMAP* dib;

		fif = FreeImage_GetFileType(filePath.c_str(), 0);
		if(fif == FIF_UNKNOWN){
			fif = FreeImage_GetFIFFromFilename(filePath.c_str());
		}

		if((fif != FIF_UNKNOWN) && FreeImage_FIFSupportsReading(fif)){
			dib = FreeImage_Load(fif, filePath.c_str(), 0);
		}

		// Convert to 32 bit format
		imageDesc->m_image = FreeImage_ConvertTo32Bits(dib);
		FreeImage_Unload(dib);

		imageDesc->m_data = FreeImage_GetBits(imageDesc->m_image);
		imageDesc->m_dataPitch = FreeImage_GetPitch(imageDesc->m_image);
		imageDesc->m_width = FreeImage_GetWidth(imageDesc->m_image);
		imageDesc->m_height = FreeImage_GetHeight(imageDesc->m_image);

		return imageDesc;
	}
}